import classnames from 'classnames';
import fetch from 'cross-fetch';

export function fetchDownload(url) {
    let promise = new Promise((resolve, reject) => {
        fetch(url).then(res => res.blob().then(blob => {
            let a = document.createElement('a');
            let url = window.URL.createObjectURL(blob); // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
            let filename = res.headers.get('Content-Disposition').split("=")[1];
            console.log(filename);
            //filename = decodeURI(filename);
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
        }).then(() => {
            resolve();
        }));
    });
    return promise;
}

// 内部函数, 用于判断对象类型
function _getClass(object) {
    return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}

export function isArray(obj) {
    return _getClass(obj).toLowerCase() === 'array';
}

export function isString(obj) {
    return _getClass(obj).toLowerCase() === 'string';
}

export function isDate(obj) {
    return _getClass(obj).toLowerCase() === 'date';
}

export function isObject(obj) {
    return _getClass(obj).toLowerCase() === 'object';
}

export function isNumber(obj) {
    return _getClass(obj).toLowerCase() === 'number' && !isNaN(obj);
}

export function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    // document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString();
    document.cookie = name + '=' + encodeURI(value);
}

export function getCookie(name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(name + '=');
        if (c_start !== -1) {
            c_start = c_start + name.length + 1;
            var c_end = document.cookie.indexOf(';', c_start);
            if (c_end === -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
}

export function clearCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;) {
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString();
        }
    }
}

/**
 * @desc 判断参数是否为空, 包括null, undefined, [], '', {}
 * @param {object} obj 需判断的对象
 */
export function isEmpty(obj) {
    var empty = false;

    if (obj === null || obj === undefined) {    // null and undefined
        empty = true;
    } else if ((isArray(obj) || isString(obj)) && obj.length === 0) {
        empty = true;
    } else if (isObject(obj)) {
        var hasProp = false;
        for (let prop in obj) {
            if (prop) {
                hasProp = true;
                break;
            }
        }
        if (!hasProp) {
            empty = true;
        }
    }
    return empty;
}

/**
 * @desc 判断参数是否不为空
 */
export function isNotEmpty(obj) {
    return !isEmpty(obj);
}

/**
 * @desc 判断参数是否为空字符串, 比isEmpty()多判断字符串中有空格的情况, 如: '   '.
 * @param {string} str 需判断的字符串
 */
export function isBlank(str) {
    if (isEmpty(str)) {
        return true;
    } else if (isString(str) && str.trim().length === 0) {
        return true;
    }
    return false;
}

/**
 * @desc 判断参数是否不为空字符串
 */
export function isNotBlank(obj) {
    return !isBlank(obj);
}

/**
 * @desc 生成一个随机id
 */
export function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

/**
 * @desc 根据对象和传入的对象value属性的值, 查询value对应的name值
 * @param {object} obj 需遍历的对象
 * @param {string} value 需搜索的value属性的值
 * @demo USER = {
 *           A: {
 *               name: '普通会员',
 *               value: 0
 *           },
 *           B: {
 *               name: 'VIP会员',
 *               value: 1
 *           }
 *       }
 */
export function searchNameByVal(obj, value) {
    if (isEmpty(obj) || isEmpty(value)) {
        return '';
    }

    for (let prop in obj) {
        if (obj[prop].value === value) {
            return obj[prop].name;
        }
    }
}

export function signKeyWords(str, words = [], color = '#00AFE3') {
    if (words.length < 1) {
        return str;
    }

    var map = {}, reg, items;
    var regStr = `(${words.join('|')})`;

    words.forEach(function (e) {
        e !== '' && (map[e] = true);
    });
    reg = new RegExp(regStr, 'g');

    items = str.replace(reg, '#$1#').split(/#+/);

    var result = [];

    for (var i = 0; i < items.length; i++) {
        if (items[i] === '') {
            continue;
        }
        if (map[items[i]]) {
            result.push(`<strong style="color: ${color};">${items[i]}</strong>`);
        } else {
            result.push(`<span>${items[i]}</span>`);
        }
    }

    return result.join('');
}

export function getTagClassName(name) {
    var blueTag = false;
    if (name.indexOf('存续') !== -1 || name.indexOf('在营') !== -1 || name.indexOf('登记') !== -1 || name.indexOf('在业') !== -1) {
        blueTag = true;
    }
    return classnames({'tag': true, 'tag-blue': blueTag, 'tag-red': !blueTag});
}

/**
 * @desc 通过URL搜索对象获取url参数, 如www.xxx.com?a=1&b=2, getURLParam('a') return 1
 */
export function getURLParam(name) {
    if (isBlank(name)) {
        return;
    }
    // var urlQuery = getURLQuery();
    var urlQuery = getQueryParams();
    return urlQuery[name];
}

export function dateFormat(formatDate) {
    return formatDate.replace(/(.{4})(.{2})/, '$1-$2-');
}

export function monthPlus(formatDate, num, showDay) { // 月份加一个月
    let date = new Date(formatDate);
    let month = date.getMonth() + num;
    date.setMonth(month);
    let temMonth = date.getMonth() + 1;
    temMonth = temMonth > 9 ? temMonth : '0' + temMonth;
    return showDay ? `${date.getFullYear()}-${temMonth}-${date.getDate()}` : `${date.getFullYear()}-${temMonth}`;
}

/*
* 获取 url 参数，因为 this.props.location.query 不能得到带有 # 的参数，所以添加此方法
* */
export function getQueryParams() {
    let obj = {}, name, value;
    let str = location.href;
    let num = str.indexOf('?');
    str = str.substr(num + 1);
    const arr = str.split('&');
    for (let i = 0; i < arr.length; i++) {
        num = arr[i].indexOf('=');
        if (num > 0) {
            name = arr[i].substring(0, num);
            value = arr[i].substr(num + 1);
            obj[name] = value;
        }
    }
    return obj;
}

/**
 * 检查元素是否在数组中
 * @param arr
 * @param obj
 * @returns {boolean}
 */
export function contains(arr, obj) {
    let i = arr.length;
    while (i--) {
        if (arr[i] === obj) {
            return true;
        }
    }
    return false;
}

/**
 * 生成随机整数
 * @param min
 * @param max
 * @constructor
 */
export function random(min, max) {
    min = min || -90;
    max = max || 90;
    return min + Math.floor(Math.random() * (max - min));
}

/**
 * 指定位置插入字符串
 * @param str
 * @param flg
 * @param sn
 * @returns {string}
 */
export function insert_flg(str, flg, sn) {
    let newstr = '';
    for (let i = 0; i < str.length; i += sn) {
        let tmp = str.substring(i, i + sn);
        newstr += tmp + flg;
    }
    return newstr;
}

export function isFormData(obj) {
    return obj instanceof FormData;
}

const keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv"
    + "wxyz0123456789+/" + "=";

export function encode64(input) {
    let output = "";
    let chr1, chr2, chr3 = "";
    let enc1, enc2, enc3, enc4 = "";
    let i = 0;
    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }
        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
            + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = "";
    } while (i < input.length);

    return output;
}

// 深克隆
export function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'shallowClone');
    }
    const targetObj = source.constructor === Array ? [] : {};
    for (const keys in source) {
        if (source.hasOwnProperty(keys)) {
            if (source[keys] && typeof source[keys] === 'object') {
                targetObj[keys] = source[keys].constructor === Array ? [] : {};
                targetObj[keys] = deepClone(source[keys]);
            } else {
                targetObj[keys] = source[keys];
            }
        }
    }
    return targetObj;
}

// 饼图或漏斗图提示框
export function getTooTipConfig() {
    let tooltip = {
        backgroundColor: 'RGBA(12, 46, 101, 0.7)',
        padding: [10, 10, 10, 10],
        trigger: 'item',
        borderWidth: 0,
        extraCssText: 'box-shadow: -3px 3px 14px 4px #053a6b',
        textStyle: {
            color: '#fff',
            fontSize: '14'
        },
        formatter: function (param) {
            let {data, percent} = param;
            let {value, name} = data;
            return `<div>
                            <span class="seriesName">${name}</span><br/>
                            <span class="seriesName">数量:</span><span class="value">${value}</span>
                            <span class="seriesName">占比:</span><span class="value">${percent}%</span>
                     <div>`;
        }
    };
    return tooltip;
};

// 柱状图或折线图提示框
export function getTooTipConfigByLineOrBar(titleNameIsNotNum = false) {
    let tooltip = {
        backgroundColor: 'RGBA(12, 46, 101, 0.7)',
        padding: [10, 10, 10, 10],
        trigger: 'item',
        borderWidth: 0,
        extraCssText: 'box-shadow: -3px 3px 14px 4px #053a6b',
        textStyle: {
            color: '#fff',
            fontSize: '14'
        },
        formatter: function (param) {
            let {data} = param;
            let {value, name} = data;
            return `<div>
                            <span class=${titleNameIsNotNum ? "seriesTitle" : "seriesTitleToNum"}>${name}</span><br/>
                            <span class="seriesName">数量:</span><span class="value">${value}</span>
                     <div>`;
        }
    };
    return tooltip;
};

export function getLineLabelConfig() {
    let labelConfig = {show: true, fontSize: "20", color: "white", fontFamily: "fontF"};
    return labelConfig;
}

export function getOtherCompanyHttp() {
    let http = 'http://10.32.209.105:8080';
    return http;
}

export function getPieOption(data, color, unit = "家") {
    let option = {
        tooltip: {
            show: false,
            backgroundColor: 'RGBA(12, 46, 101, 0.7)',
            padding: [10, 10, 10, 10],
            trigger: 'item',
            borderWidth: 0,
            extraCssText: 'box-shadow: -3px 3px 14px 4px #053a6b',
            textStyle: {
                color: '#333333',
                fontSize: '14'
            },
            formatter: function (param) {
                let {data, percent} = param;
                let {value, name} = data;
                return `<div>
                                    <span class="seriesName">${name}</span><br/>
                                    <span class="seriesName">数量:</span><span class="value">${value}</span>
                                    <span class="seriesName">占比:</span><span class="value">${percent}%</span>
                             <div>`;
            }
        },
        series: [
            {
                name: '风险企业',
                type: 'pie',
                radius: ['18%', '65%'],
                center: ['50%', '50%'],
                roseType: 'radius',
                data: data,
                minAngle: 5,
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                color: color,
                label: {
                    normal: {
                        formatter: `{b|{b}}\n{c}${unit}  {per|{d}%}  `,
                        backgroundColor: 'RGBA(12, 46, 101, 0)',
                        borderWidth: 1,
                        borderRadius: 4,
                        padding: [2, 2],
                        rich: {
                            b: {
                                fontSize: 12,
                                lineHeight: 25,
                                align: 'left'
                            },
                            c: {
                                fontSize: 12,
                                lineHeight: 25,
                                align: 'left'
                            },
                            per: {
                                lineHeight: 25,
                                padding: [2, 4],
                                borderRadius: 2
                            }
                        }
                    }
                },
            }
        ]
    }
    return option;
}

export function getLineXyOption(xName, xDataArray, yName) {
    let option = {
        xAxis: {
            name: xName,
            type: 'category',
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    type: 'solid',
                    color: '#03F5F6',//左边线的颜色
                }
            },
            axisLabel: {
                color: '#fff'
            },
            data: xDataArray
        },
        yAxis: {
            name: yName,
            type: 'value',
            axisTick: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    type: 'solid',
                    color: '#03F5F6',//左边线的颜色
                }
            },
            splitLine: {
                lineStyle: {
                    color: "rgb(58,93,147,0.7)"
                }
            },
            axisLabel: {
                color: '#fff'
            },
        },
    };
    return option;
}

export const ringPieLabelOption = {
    normal: {
        show: false,
        position: 'center'
    },
    emphasis: {
        show: true,
        textStyle: {
            fontSize: '27',
            fontWeight: 'bold'
        },
        formatter: function (params) {
            let result = '';
            let name = params.name;
            let name1 = '';
            if (name.slice(7, 14) && name.slice(7, 14) !== '') {
                name1 += '\n' + name.slice(7, 14);
            }
            if (name.slice(14, 21) && name.slice(14, 21) !== '') {
                name1 += '\n' + name.slice(14, 21);
            }
            if (name.slice(21) && name.slice(21) !== '') {
                name1 += '\n' + name.slice(21);
            }
            result +=
                '{a|' + params.percent.toFixed(2) + '% }' + '\n' +
                '{b|' + name.slice(0, 7) + name1 + '}'
            ;
            return result
        },
        rich: {
            a: {
                color: '#ffce31',
                fontSize: 22,
                fontWeight: 600,
            },
            b: {
                color: '#fff',
                fontSize: 14,
            }
        }
    }
}

export function getTableIndex(index, start, size = 10) {
    return index + 1 + (start - 1) * size;
}

export function getIndustryOneAndTow(condition = {}, firstIndustry = "全部行业", secondIndustry = "全部子行业") {
    condition.industryOne = firstIndustry === "全部行业" ? "" : firstIndustry;
    condition.industryTwo = secondIndustry === "全部子行业" ? "" : secondIndustry;
    return condition;
}